package com.rui.study.micro.oauth2.controller;


import com.rui.study.commons.model.BaseController;
import com.rui.study.commons.model.Result;
import com.rui.study.commons.util.Base64Util;
import com.rui.study.commons.util.RSAUtil;
import com.rui.study.micro.oauth2.model.AccountDTO;
import com.rui.study.micro.oauth2.model.LoginGroup;
import com.rui.study.micro.oauth2.service.AccountService;
import com.rui.study.micro.oauth2.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @program: study_20180824
 * @description: Oauth2控制器
 * @author: Yaowr
 * @create: 2018-08-29 10:01
 **/
@RestController
@RefreshScope
public class Oauth2Controller extends BaseController {

    @Autowired
    private AccountService accountService;

    @Value("${encrypt.local.pub-key}")
    private String pubKey;

    @Value("${encrypt.local.pri-key}")
    private String priKey;


    @PostMapping("/v1/auth")
    public Result<String> auth(@Validated(LoginGroup.class) @RequestBody AccountDTO accountDTO) {
        String jwt = accountService.auth(accountDTO.getUsername(), accountDTO.getPassword());
        return new Result(StatusCode.SUCCEED, jwt);
    }


    @GetMapping("/v1/check")
    public Result<String> check(@RequestParam("token") String token) {
        String accountId = accountService.check(token);
        return new Result(StatusCode.SUCCEED, accountId);
    }


    @PostMapping(value = "/encrypt")
    public Result<String> encrypt(@RequestBody String data) {
        try {
            String encData = Base64Util.encode(RSAUtil.encryptByPublicKey(data.getBytes(), pubKey));
            return new Result<>(StatusCode.SUCCEED, new String(encData));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @PostMapping(value = "/decrypt")
    public Result<String> decrypt(@RequestBody String encData) {
        try {
            byte[] bytes = RSAUtil.decryptByPrivateKey(Base64Util.decode(encData), priKey);
            return new Result<>(StatusCode.SUCCEED, new String(bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
